$(document).ready(function () {
	$("#balance").hide();
	$("#statement").hide();
	$('.popUp').popupWindow({ 
		windowURL:"help.html",
		windowName: "Help",
		height:600, 
		width:800, 
		top:50, 
		left:50,
		centerBrowser:1 
	}); 
});

function ajaxError(jqXHR, textStatus, errorThrown){
	alert("Errore: "+textStatus);
	window.location = "../unsecure/ajaxError.html"
	
}

function appendStatementItems (xml) {
	//cleanup //
	$("#balanceList").empty();
	var items = $(xml).find("response").find("statement").find("item");
	for (i=0;i<items.length;i++){
		appendStatementItem(
			$(items[i]).attr("id"),
			$($(items[i]).find("date")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("price")[0]).text(),
			$($(items[i]).find("name")[0]).text(),
			$($(items[i]).find("description")[0]).text()
		);
	}
}

function appendStatementItem (id,date,name,price,itemName,description){
	var	strVar = "\n"+"<form id=\""+id+ "\">";
		strVar +="\n"+ "                 <input type=\"hidden\" name=\"recordID\" disabled=\"disabled\" value=\""+id+"\"/>";
		strVar += "\n"+"					<ul>";
		strVar += "\n"+"						<li>";
		strVar +="\n"+ "							<input type=\"date\" name=\"date\" class=\"itemDate\" disabled=\"disabled\" required=\"required\"\ value=\""+date+"\"/>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"price\" class=\"itemPrice\" disabled=\"disabled\" required=\"required\" pattern=\"^\\\d+(\\,)\\d{2}$\" value=\""+price+"\" title=\"Completare nel formato #,00 es: 10,68\"/>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"name\" class=\"itemName\" disabled=\"disabled\" required=\"required\" value=\""+name+"\"/>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"						<li>";
		strVar += "\n"+"							<input type=\"text\" name=\"description\" class=\"itemDescription\" disabled=\"disabled\" value=\""+description+"\"/>";
		strVar += "\n"+"						<\/li>";
		strVar += "\n"+"					<\/ul>";
		strVar += "\n"+"				<\/form>";
		
		$("#balanceList").prepend(strVar);
}
	
function performStatementSum(xml){
	var sum = 0;
	var items = $(xml).find("response").find("statement").find("item");
	for (i=0;i<items.length;i++)
			sum += parseFloat($($(items[i]).find("price")[0]).text().replace(",","."));
	
	$("#balance .money").text(sum.toFixed(2).replace(".",",") + " \u20ac");
}


function XMLRequestGenerator(startDate,stopDate,name,description){

	var xw = new XMLWriter( 'UTF-8', '1.0' );
	xw.formatting = 'indented';//add indentation and newlines
	xw.indentChar = ' ';//indent with spaces
	xw.indentation = 2;//add 2 spaces per level
	
	
	xw.writeStartDocument( );
	
	xw.writeStartElement( 'query' );
			
	xw.writeElementString('startDate',startDate);
	xw.writeElementString('stopDate',stopDate);
	xw.writeElementString('name',name);
	xw.writeElementString('description',description);
	
	xw.writeEndElement();
	
	
	xw.writeEndElement();
	xw.writeEndDocument();
	
	return xw.getDocument();
}


var XMLResponseAnalizer = (function(){
	
	
	var isError = function(xmlResponse){
		var exitStatus = $(xmlResponse).find("exitStatus").attr("status");
		if ( exitStatus === "OK")
			return false;
		return true;
		
	}
	var exitStatus = function(xmlResponse){
		return $(xmlResponse).find("exitStatus").children("description").text;	
	}
	
	return {
		isError: isError,
		exitStatus: exitStatus,
	};
	
})();



function submitSearch(button){
	try{
	//Workaround
	var form =  document.getElementById ($(button).parents("form").attr("id"));
	
	//----------------------
	$(button).parents("form").removeAttr("novalidate");
	if (!form.checkValidity()){
		return  false;
	}

	var xmlData = XMLRequestGenerator($("#startDate").val(),$("#stopDate").val(),$("#itemName").val(),$("#description").val());
	
	$.ajax({  
	    type: "POST",  
	    url: "queryStatement",  
	    dataType: "xml",
	    processData: false,
	    data: xmlData,
	    success: function(xml){
	    	try{
	    		if (XMLResponseAnalizer.isError(xml)){
	    			ajaxError(undefined, XMLResponseAnalizer.exitStatus(xml));
	    		}else{
	    			performStatementSum(xml);
	    			appendStatementItems(xml);
	    			$("#balance").show();
	    			$("#statement").show();
	    			uiManager.unBlockUI();
	    		}
	    	}catch (exception){
	    		ajaxError();
	    	}
	    },
	    error: ajaxError,
	    beforeSend: function() {
	    	uiManager.blockUI("Attendere, prego","Interrogazione in corso...");
	    },
	}); 
	
	$(button).parents("form").attr("novalidate","novalidate");
	
	}catch (e){
		alert(e);
	}
	
	return true;
	
}


var uiManager = (function(){
	
	var blockTime;
	var blockUI = function (title, message){
	
		blockTime =  new Date();
		try{
			$("#growlUI").remove();
		}finally{
			$(document.body).append("<div id=\"growlUI\"></div>");
			$("#growlUI").hide();
			$("#growlUI").attr("class","growlUI");
			$("#growlUI").append("<h1>"+title+"</h1>");
			$("#growlUI").append("<h2>"+message+"</h2>");
			$("#growlUI").append("<img src=\"img/ajaxLoader.gif\" alt =\"ajaxLoaderImage\"/>");
			
			
			
			$.blockUI({ 
	            message: $('div.growlUI'), 
	            fadeIn: 700, 
	            fadeOut: 700,  
	            showOverlay: true, 
	            centerY: false, 
	            css: { 
	                width: '350px', 
	                top: '10px', 
	                left: '', 
	                right: '10px', 
	                border: 'none', 
	                padding: '5px', 
	                backgroundColor: '#000', 
	                '-webkit-border-radius': '10px', 
	                '-moz-border-radius': '10px', 
	                opacity: .6, 
	                color: '#fff' 
	            } 
	        }); 
		}
		
	}

	var unBlockUIAction=function(){
		$.unblockUI();
		$("#growlUI").remove();
	}
	var unBlockUI = function (){
		

		var minDelta = 2000; //mindelay
		var delta = new Date() - blockTime;
		if (delta < minDelta)
			setTimeout(function(){unBlockUIAction()},minDelta-delta);
		else
			unBlockUIAction();
	
	}
	return{
		unBlockUI: unBlockUI,
		blockUI: blockUI
	}
})();







function onStopDateChange(element){
	$("#startDate").attr("max",$(element).val());
}

function onStartDateChange(element){
	$("#stopDate").attr("min",$(element).val());
}
















 